package batch.home;

import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import com.samsungmobile.nordic.funclub.funclub.services.Contents.*;

import java.io.*;
import java.util.*;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.*;

public class makeHomeForNrd extends DefaultHandler
{
    private final String TODAY         = DateFormatUtils.format(new Date(), "yyyyMMdd");  //Get Current Date
    private final String IMAGE_URL     = "/eng/images/main/";
    private final String FILE_PATH     = "/home01/sfc/batch/home/data/nrd_home/" + TODAY;    

    private final String GO_RINGTONES  = "link/goPremium.jsp?mcate_cd=RING";
    private final String RINGTONE_PATH    = "link/goPremium.jsp?mcate_cd=A1&content_id=";

    private final String GO_IMAGES     = "link/goPremium.jsp?mcate_cd=IMG";
    private final String IMAGE_PATH    = "link/goPremium.jsp?mcate_cd=08&content_id=";

    private final String GO_JAVAGAMES  = "link/goPremium.jsp?mcate_cd=GAME";
    private final String JAVAGAME_PATH = "link/goPremium.jsp?mcate_cd=04&content_id=";

    boolean isContent_id;
    boolean isContent_name;
    boolean isContent_url;

    Hashtable hData;
    Vector vContens;

    String[] aContent;

    public static void main( String args[] ){
        Logger.getLogger("home.nrd_home").info("########  Start  ##########");
        makeHomeForNrd mgr = new makeHomeForNrd();
        if(args[0].equals("all")){
            mgr.getAllContentList(args[1]);
        }else{
            mgr.getContentList(args[0],args[1]);
        }
        Logger.getLogger("home.nrd_home").info("########  End  ##########");
    }

    public makeHomeForNrd(){}

    public void getAllContentList(String count){
        try{
            PubContentsService service = new PubContentsServiceLocator();
            PubContents port = service.getContents();
            String xml = port.getAllContentList(Integer.parseInt(count));
            xmlParsing_start(xml);

            File fl = new File(FILE_PATH);
            if(!fl.isDirectory()){
                fl.mkdirs();
            }
            //return hData;
            if(hData != null){
                if(hData.get("A1")!=null && ((Vector)hData.get("A1")).size() != 0)
                    writeRingtone((Vector)hData.get("A1"));

                if(hData.get("07")!=null && ((Vector)hData.get("07")).size() != 0){
                	writeImage((Vector)hData.get("07"));
                }else if(hData.get("08")!= null && ((Vector)hData.get("08")).size() != 0){
                    //writeImage((Vector)hData.get("08"));
                }

                if(hData.get("04")!=null && ((Vector)hData.get("04")).size() != 0)
                    writeGame((Vector)hData.get("04"));
            }

        }catch(Exception e){
            Logger.getLogger("home.nrd_home").info("########  NRD ERROR ##########");
            Logger.getLogger("home.nrd_home").info(e.toString());
        }
    }

    public void getContentList(String mcate_cd , String count){
        try{
            PubContentsService service = new PubContentsServiceLocator();
            PubContents port = service.getContents();
            String xml = port.getContentList(mcate_cd, Integer.parseInt(count));
            xmlParsing_start(xml);
        }catch(Exception e){
            Logger.getLogger("home.nrd_home").info(e.toString());
        }
    }

    public void xmlParsing_start(String xml) throws Exception{
        SAXParserFactory  factory = SAXParserFactory.newInstance( );
        SAXParser parser = factory.newSAXParser();
        byte[] bxml=xml.getBytes("UTF-8");
        ByteArrayInputStream is = new ByteArrayInputStream(bxml);
        parser.parse(is, this);
    }

    public void startDocument() throws SAXException{}

    public void endDocument() throws SAXException {}

    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException{
        if(qName.equals("CONTENTS")){
            vContens = new Vector();
        }else if(qName.equals("ALL_CONTENTS")){
            hData = new Hashtable();
        }else if(qName.equals("RINGTONES")){
            vContens = new Vector();
        }else if(qName.equals("WALLPAPERS")){
            vContens = new Vector();
        }else if(qName.equals("SCREENSAVERS")){
            vContens = new Vector();
        }else if(qName.equals("GAMES")){
            vContens = new Vector();
        }else if(qName.equals("CONTENT")){
            aContent = new String[3];
        }else if(qName.equals("CONTENT_ID")){
            isContent_id = true;
        }else if(qName.equals("CONTENT_NAME")){
            isContent_name = true;
        }else if(qName.equals("PREVIEW_URL")){
            isContent_url = true;
        }
    }

    public void endElement(String uri,String localName, String qName) throws SAXException{
        if(qName.equals("CONTENTS")){

        }else if(qName.equals("ALL_CONTENTS")){

        }else if(qName.equals("RINGTONES")){
            hData.put("A1", vContens);
            vContens = null;
        }else if(qName.equals("WALLPAPERS")){
            hData.put("08", vContens);
            vContens = null;
        }else if(qName.equals("SCREENSAVERS")){
            hData.put("07", vContens);
            vContens = null;
        }else if(qName.equals("GAMES")){
            hData.put("04", vContens);
            vContens = null;
        }else if(qName.equals("CONTENT")){
            vContens.add(aContent);
            aContent = null;
        }else if(qName.equals("CONTENT_ID")){
            isContent_id = false;
        }else if(qName.equals("CONTENT_NAME")){
            isContent_name = false;
        }else if(qName.equals("PREVIEW_URL")){
            isContent_url = false;
        }
    }

    public void characters( char[] ch, int start, int len ){
        if(isContent_id){
            aContent[0] = new String(ch, start, len )  == null? "" : new String(ch, start, len );
        }else if(isContent_name){
            aContent[1] = new String(ch, start, len )  == null? "" : new String(ch, start, len );
        }else if(isContent_url){
            aContent[2] = new String(ch, start, len )  == null? "" : new String(ch, start, len );
        }
    }

    public void ignorableWhitespace(char ch[], int start, int length ) throws SAXException{}

    public void writeRingtone(Vector ringtones) throws Exception{
        OutputStreamWriter fw = null;
        try{
            int count = 0;
            if(ringtones != null){
                if(ringtones.size() > 5){
                    count = 5;
                }else{
                    count = ringtones.size();
                }
            }
            if(ringtones != null && ringtones.size() > 0){
                StringBuffer stContent = new StringBuffer();
                stContent.append("<table width=191 cellpadding=0 cellspacing=0> \n")
                         .append("<form name='frm_list'> \n")
                         .append("    <tr> \n")
                         .append("        <td height=29 style='background-image : url(" + IMAGE_URL + "bg_box02_01.gif)' align=center> \n")
                         .append("            <table width=170 cellpadding=0 cellspacing=0> \n")
                         .append("                <tr> \n")
                         .append("                    <td><a href=" + GO_RINGTONES + "><img src='" + IMAGE_URL + "title_ringtones.gif' align=absmiddle></a></td>    \n")
                         .append("                    <td width=36><a href=" + GO_RINGTONES + "><img src='" + IMAGE_URL + "bn_more01.gif' align=absmiddle></a></td> \n")
                         .append("                </tr> \n")
                         .append("            </table> \n")
                         .append("        </td> \n")
                         .append("    </tr> \n")
                         .append("    <tr> \n")
                         .append("        <td height=114 style='background-image : url(" + IMAGE_URL + "bg_box02_02.gif);padding:5 0 0 0' align=center valign=top>  \n")
                         .append("            <table width=183 cellpadding=0 cellspacing=0> \n")
                         .append("                <col width=8> \n")
                         .append("                <col width=160> \n")
                         .append("                <col width=10> \n")
                         .append("                <col width=5> \n");
                for(int i=0; i<count; i++){
                  String[] aRingtone = (String[])ringtones.elementAt(i);

                  String sUrl = RINGTONE_PATH + aRingtone[0];

                  stContent.append("            <tr bgcolor=#F7FEFF>                                                                                              \n")
                           .append("                <td><img src='" + IMAGE_URL + "bg_box02_03.gif' align=absmiddle></td>                                         \n")
                           .append("                <td><a href='" + sUrl + "' >" + sub_string(aRingtone[1],20) + "</a></td>                                              \n")
                           .append("                <td><a href='javascript:playMusic("+aRingtone[0]+");' ><img src='" + IMAGE_URL + "bn_sound.gif' align=absmiddle></a></td>       \n")
                           .append("                <td align=right><img src='" + IMAGE_URL + "bg_box02_04.gif' align=absmiddle></td>                             \n")
                           .append("            </tr>\n");

                  if ( i < (count - 1) ) {
                    stContent.append("        <tr><td colspan=4 height=1></td></tr>                                                                             \n");
                  }
                }

                stContent.append("            </table> \n")
                         .append("        </td> \n")
                         .append("    </tr> \n")
                         .append("</form> \n")
                         .append("</table> \n");

                fw = new OutputStreamWriter(new FileOutputStream(FILE_PATH + "/ringtone_include.html", false), "UTF-8");
                fw.write(stContent.toString());

                fw.close();
                fw = null;
            }
        }finally{
            if (fw != null) try { fw.close(); } catch (Exception e) {}
        }
    }

    public void writeGame(Vector games) throws Exception{
        OutputStreamWriter fw = null;
        try{
            if(games != null && games.size() > 0){
                StringBuffer stContent = new StringBuffer();
                stContent.append("<table width=191 cellpadding=0 cellspacing=0> \n")
                         .append("    <tr height=29> \n")
                         .append("        <td style='background-image : url(" + IMAGE_URL + "bg_title_01.gif)' align=center > \n")
                         .append("            <table width=170 cellpadding=0 cellspacing=0> \n")
                         .append("                <tr> \n")
                         .append("                    <td><a href=" + GO_JAVAGAMES + "><img src='" + IMAGE_URL + "title_mobile_games.gif' align=absmiddle></a></td> \n")
                         .append("                    <td width=36><a href=" + GO_JAVAGAMES + "><img src='" + IMAGE_URL + "bn_more02.gif' align=absmiddle></a></td> \n")
                         .append("                </tr> \n")
                         .append("            </table> \n")
                         .append("        </td> \n")
                         .append("    </tr> \n")
                         .append("    <tr><td height=2></td></tr> \n")
                         .append("    <tr> \n")
                         .append("        <td height=112 style='background-image : url(" + IMAGE_URL + "bg_box03.gif);padding:13 0 0 0' align=center valign=top> \n")
                         .append("            <table width=166 cellpadding=0 cellspacing=0> \n")
                         .append("                <tr> \n");
                for(int i=0; i<2&&i<games.size(); i++){
                  String[] aGame = (String[])games.elementAt(i);

                  String sUrl = JAVAGAME_PATH + aGame[0];

                  stContent.append("                    <td> \n")
                           .append("                        <table width=79 cellpadding=1 cellspacing=0 > \n")
                           .append("                            <tr height=79> \n")
                           .append("                                <td bgcolor=#9AA9B4 ><a href='"+sUrl+"'><img src='" + aGame[2] + "' width=77 height=77 align=absmiddle></a></td> \n")
                           .append("                            </tr> \n")
                           .append("                            <tr><td class=f_09 style='padding:3 0 0 0'><img src='" + IMAGE_URL + "icon_02.gif' align=absmiddle>&nbsp;<a href=href='"+sUrl+"'>" + sub_string(aGame[1],10) + "</a></td></tr> \n")
                           .append("                        </table> \n")
                           .append("                    </td> \n");
                  if(i%2 == 0)  stContent.append("                    <td width=8></td> \n");
                }
                stContent.append("            </table> \n")
                         .append("        </td> \n")
                         .append("    </tr> \n")
                         .append("</table> \n");


                fw = new OutputStreamWriter(new FileOutputStream(FILE_PATH + "/game_include.html", false), "UTF-8");
                fw.write(stContent.toString());

                fw.close();
                fw = null;
            }
        }finally{
            if (fw != null) try { fw.close(); } catch (Exception e) {}
        }
    }

    public void writeImage(Vector images) throws Exception{
        OutputStreamWriter fw = null;
        try{
            if(images != null && images.size() > 0){
                StringBuffer stContent = new StringBuffer();
                stContent.append("<table width=191 cellpadding=0 cellspacing=0> \n")
                         .append("    <tr height=29> \n")
                         .append("        <td style='background-image : url(" + IMAGE_URL + "bg_title_02.gif)' align=center > \n")
                         .append("            <table width=170 cellpadding=0 cellspacing=0> \n")
                         .append("                <tr> \n")
                         .append("                    <td><a href=" + GO_IMAGES + "><img src='" + IMAGE_URL + "title_screensavers.gif' align=absmiddle></a></td> \n")
                         .append("                    <td width=36><a href=" + GO_IMAGES + "><img src='" + IMAGE_URL + "bn_more03.gif' align=absmiddle></a></td> \n")
                         .append("                </tr> \n")
                         .append("            </table> \n")
                         .append("        </td> \n")
                         .append("    </tr> \n")
                         .append("    <tr><td height=2></td></tr> \n")
                         .append("    <tr> \n")
                         .append("        <td height=112 style='background-image : url(" + IMAGE_URL + "bg_box03.gif);padding:13 0 0 0' align=center valign=top> \n")
                         .append("            <table width=166 cellpadding=0 cellspacing=0> \n")
                         .append("                <tr> \n");
                for(int i=0; i<2&&i<images.size(); i++){
                  String[] aImage = (String[])images.elementAt(i);
                  String sUrl = IMAGE_PATH + aImage[0];

                  stContent.append("                    <td> \n")
                           .append("                        <table width=79  cellpadding=1 cellspacing=0 > \n")
                           .append("                            <tr height=79> \n")
                           .append("                                <td bgcolor=#9AA9B4><a href='"+sUrl+"'><img src='" + aImage[2] + "' width=77 height=77 align=absmiddle></a></td> \n")
                           .append("                            </tr> \n")
                           .append("                            <tr><td class=f_09 style='padding:3 0 0 0'><img src='" + IMAGE_URL + "icon_02.gif' align=absmiddle>&nbsp;<a href='"+sUrl+"'>" + sub_string(aImage[1],10) + "</a></td></tr> \n")
                           .append("                        </table> \n")
                           .append("                    </td> \n");
                  if(i%2 == 0)  stContent.append("                    <td width=8></td> \n");
                }
                stContent.append("                </tr> \n")
                         .append("            </table> \n")
                         .append("        </td> \n")
                         .append("    </tr> \n")
                         .append("</table> \n");

                fw = new OutputStreamWriter(new FileOutputStream(FILE_PATH + "/image_include.html", false), "UTF-8");
                fw.write(stContent.toString());

                fw.close();
                fw = null;
            }
        }finally{
            if (fw != null) try { fw.close(); } catch (Exception e) {}
        }
    }

    public String sub_string(String s, int i)
    {
        int title_length = (s.length() >= i) ? i : s.length();

        s = s.substring(0,title_length);
        return (s.length() < i) ? s : s+"..";
    }

}